package com.whz.gateway.common.convert;

import org.springframework.http.MediaType;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.function.BiFunction;
import java.util.function.Function;

/**
 * @author whz
 * @date 2021/8/30
 */
public class StringToJsonConverter extends Convert<String, String> {

    public StringToJsonConverter(final Function<String, String> function) {
        setInClass(String.class);
        setOutClass(String.class);
        setContentType(MediaType.APPLICATION_JSON_VALUE);
        setRewriteFunction((exchange, body) -> Mono.defer(() -> {
            String newBody = function.apply(body);
            // 返回新的body
            return Mono.just(newBody);
        }));
    }

    public StringToJsonConverter(final BiFunction<ServerWebExchange, String, String> function) {
        setInClass(String.class);
        setOutClass(String.class);
        setContentType(MediaType.APPLICATION_JSON_VALUE);
        setRewriteFunction((exchange, body) -> Mono.defer(() -> {
            String newBody = function.apply(exchange, body);
            // 返回新的body
            return Mono.just(newBody);
        }));
    }
}